package verify

import (
	"errors"
	"net/http"

	"frame/internal/app/user/httputils/user/dto/request"
	"frame/internal/app/user/httputils/user/handler"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

// 初始化 validator
var validate = validator.New()

// UserVerifyHandler 处理用户验证请求
func UserVerifyHandler(c *gin.Context) {
	var req request.VerifyRequest

	// 解析并绑定 JSON 请求体
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request: " + err.Error()})
		return
	}

	// 验证请求数据
	if err := validate.Struct(req); err != nil {
		validationErrors := parseValidationErrors(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Validation failed", "details": validationErrors})
		return
	}

	// 调用业务逻辑
	if verifyUser(req.Email, req.Code) {
		handler.UserHandler(c, req) // 处理用户逻辑
		c.JSON(http.StatusOK, gin.H{"message": "Verification successful"})
	} else {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Verification failed"})
	}
}

// verifyUser 模拟控制器逻辑
func verifyUser(email, code string) bool {
	// 具体实现验证逻辑，例如查询数据库或调用外部服务
	// 示例：仅当邮箱和验证码匹配时验证成功
	return email == "test@example.com" && code == "123456"
}

// parseValidationErrors 将 validator 错误解析为用户友好的信息
func parseValidationErrors(err error) map[string]string {
	errorMsg := make(map[string]string)
	var validationErrors validator.ValidationErrors
	if errors.As(err, &validationErrors) {
		for _, fieldError := range validationErrors {
			errorMsg[fieldError.Field()] = fieldError.Tag() // 显示失败的字段及验证规则
		}
	}
	return errorMsg
}
